﻿using System;
using System.IO;
using System.Net;

using HttpService.Helper;
using HttpService.Model;

namespace HttpService.Handler
{

    internal class FileHandler : BasicHandler
    {
        private DirConfig _Config;
        public FileHandler(string regex, DirConfig config, short sortNum) : base(regex, sortNum, true)
        {
            _Config = config;
        }
        protected virtual string GetFilePath()
        {
            return FileHelper.GetFilePath(this.Request.Url, _Config);
        }

        public override void Execute()
        {
            string path = this.GetFilePath();
            if (string.IsNullOrEmpty(path) || !File.Exists(path))
            {
                this.Response.SetHttpStatus(HttpStatusCode.NotFound);
                return;
            }
            FileInfo file = new FileInfo(path);
            if (this.LoadFile(file))
            {
                this.Response.WriteFile(file);
            }
        }
        protected virtual bool LoadFile(FileInfo file)
        {
            if (_Config.isCache)
            {
                this.Response.SetCache(file.LastWriteTime, _Config.cacheTime);
            }
            return true;
        }

        protected override bool CheckCache(string etag, string toUpdateTime)
        {
            if (string.IsNullOrEmpty(toUpdateTime))
            {
                return false;
            }
            string filePath = this.GetFilePath();
            if (!string.IsNullOrEmpty(filePath))
            {
                DateTime time = File.GetLastWriteTime(filePath);
                DateTime myTime = DateTime.Parse(toUpdateTime);
                return myTime < time;
            }
            return false;
        }
    }
}
